import hashlib
import Transaction
class ProofOfWork:
    """
        工作量证明
    """
    def __init__(self, block,miner,difficult=5):
        self.block = block
        # 定义工作量难度， 默认为5 ，标识有效的哈希值以5个0开头
        self.difficult = difficult
        # 添加挖矿奖励
        self.reward_amount = 1

    def mine(self):
        """
            挖矿函数
        """
        i = 0
        # 00000 前缀
        prefix = '0' * self.difficult

        while True:
            message = hashlib.sha256()
            message.update(str(self.block.prev_hash).encode("utf-8"))
            message.update(str(self.block.data).encode("utf-8"))
            message.update(str(self.block.timestamp).encode("utf-8"))
            # 随机数 暴力 i
            message.update(str(i).encode("utf-8"))
            digest = message.hexdigest()
            # 判断前缀是否是以prefix开头
            if digest.startswith(prefix):
                self.block.nonce = i
                self.block.hash = digest
                return self.block
            # 穷举
            i+=1
        # 添加奖励
        t = Transaction(
            sender = "",
            recipient = self.miner
        )

    def validate(self):
        """
            验证有效性
        """
        message = hashlib.sha256()
        message.update(str(self.block.prev_hash).encode("utf-8"))
        message.update(str(self.block.data).encode("utf-8"))
        message.update(str(self.block.timestamp).encode("utf-8"))
        message.update(str(self.block.nonce).encode("utf-8"))
        digest = message.hexdigest()
        prefix = '0' * self.difficult
        return digest.startswith(prefix)
